<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
    <link crossorigin='anonymous' href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">axios取消请求</h2>
        <button class="btn btn-primary">发送请求</button>
        <button class="btn btn-warning">取消请求</button>
    </div>
    <script>
        //获取按钮
        const btns =document.querySelectorAll('button');
        //2 声明全局变量
        let  cancel=null;
            //发送请求
        btns[0].onclick=function(){
            if(cancel !== null){
                //取消上一次请求
                cancel();
            }
                axios({
                    method:'GET',
                    url:'http://localhost:3000/posts',
                    //添加配置对象的属性
                    cancelToken: new axios.CancelToken(function (c) {
                        //3将c的值赋值给cancel
                        cancel = c;
                    })
                }).then(response => {
                        console.log(response);
                       //将cancel的值初始化
                        cancel= null;
                })
            }

            //绑定第二个事件取消请求
            btns[1].onclick=function(){
                cancel();
            }
</script>
</body>
</html>